<?php

/**
 * Class Core_Gearman
 * @package Core
 */
class Core_Gearman {
    // Singleton instances
    protected static $_clientInstance;
    protected static $_workerInstance;

    const CLIENT_TIMEOUT = 2000;
    const WORKER_TIMEOUT = 60000;
    const MAX_RETRY = 3;

    /**
     * @param string $name
     * @return GearmanClient
     */
    public static function getClient($name = 'default') {
        if (empty(self::$_clientInstance[$name])) {
            $conf = Core_Config::get("gearman.{$name}");

            $client = false;
            $retry = self::MAX_RETRY;
            while (!$client && $retry--) {
                $client = self::_connClient($conf['host'], $conf['port']);
            }

            self::$_clientInstance[$name] = $client;
        }
        return self::$_clientInstance[$name];
    }

    protected static function _connClient($host, $port) {
        $client = new GearmanClient();
        $client->addServer($host, $port);
        $client->setTimeout(self::CLIENT_TIMEOUT); #-1 means never, as default value
        try {
            $client->ping('ping');
        } catch (Exception $e) {
            //connection lost, try again
            Core_Log::logErr($e);
            return false;
        }
        return $client;
    }

    public static function closeClient($name = 'default') {
        if (!empty(self::$_clientInstance[$name])) {
            unset(self::$_clientInstance[$name]);
        }
    }

    /**
     * @param string $name
     * @return GearmanWorker
     */
    public static function getWorker($name = 'default') {
        if (empty(self::$_workerInstance[$name])) {
            $conf = Core_Config::get("gearman.{$name}");
            $worker = new GearmanWorker();
            $worker->addServer($conf['host'], $conf['port']);
            $worker->setTimeout(self::WORKER_TIMEOUT);
            self::$_workerInstance[$name] = $worker;
        }
        return self::$_workerInstance[$name];
    }
}
